<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">Login Form</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="Password"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-form-item prop="captcha">
        <span class="svg-container">
          <svg-icon icon-class="captcha" />
        </span>
        <el-input
          v-model="loginForm.captcha"
          placeholder="Captcha"
          name="captcha"
          type="text"
          tabindex="3"
          auto-complete="off"
        />
        <!-- 验证码图片 -->
        <span class="captcha-image" @click="getCaptcha">
          <img :src="captchaImageUrl" alt="Captcha" style="width: 120px; height: 40px; margin-left: 10px; cursor: pointer;" />
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>

      <div class="tips">
        <span style="margin-right:20px;">username: admin</span>
        <span> password: admin@Erp.</span>
      </div>

    </el-form>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { validUsername } from '@/utils/validate'
import axios from 'axios' // 局部引入axios

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    const validateCaptcha = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error('Please enter captcha'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: 'admin@Erp.',
        captcha: '', // 清空默认值，由用户输入
        checkKey: null, // 存储验证码对应的时间戳
        remember_me: true
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        captcha: [{ required: true, trigger: 'blur', validator: validateCaptcha }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      captchaImageUrl: '' // 存储验证码图片地址
    }
  },
  watch: {
    $route(route) {
      this.redirect = route.query.redirect;
      // immediate: true
    }
  },
  mounted() {
    // 组件挂载后立即获取验证码
    this.getCaptcha()
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 获取验证码图片
    async getCaptcha() {
      const timestamp = Date.now() // 生成当前时间戳作为checkKey
      this.loginForm.checkKey = timestamp // 保存时间戳到表单
      try {
        const response = await axios.get(
          `http://api.erp.byesame.com/jeecg-boot/sys/randomImage/${timestamp}`
        )
          this.captchaImageUrl = response.data.result // 设置图片地址
      } catch (error) {
        console.error('Captcha request error:', error)
        this.$message.error('Captcha load failed, please try again')
      }
    },
    // 修改登录逻辑
    async handleLogin() {
      this.loading = true;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          const loginData = {
            ...this.loginForm, // 包含checkKey和captcha
            username: this.loginForm.username.trim(),
            password: this.loginForm.password.trim(),
            remember_me: this.loginForm.remember_me
          }
          // 使用axios发送POST请求
          axios.post('http://api.erp.byesame.com/jeecg-boot/sys/login', loginData)
            .then(response => {
              if (response.data.code == 200) {
                // 存储token到cookie
                localStorage.setItem('token', response.data.result.token);
                // 修改跳转地址
                 this.$store.dispatch('user/login', this.loginForm).then(() => {
                  this.$router.push({ path: this.redirect || '/' });
                 })
              } else {
                this.getCaptcha();
                this.$message.error(response.data.message)
              }
              this.loading = false
            })
            .catch(error => {
              this.getCaptcha();
              console.error('登录请求失败:', error)
              Message.error('登录失败，请检查网络或重试')
              this.loading = false
            })
        } else {
          this.loading = false;
          Message.error('请填写正确表单信息');
          this.getCaptcha();
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: $light_gray;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  /* 验证码图片样式 */
  .captcha-image {
    display: inline-block;
    vertical-align: middle;
  }
}
</style>